// 预定义的颜色集合
const PREDEFINED_COLORS = [
  '#ff6b6b', '#4ecdc4', '#45b7d1', '#f9ca24', '#f0932b',
  '#eb4d4b', '#6c5ce7', '#fd79a8', '#fdcb6e', '#fd79a8',
  '#55efc4', '#81ecec', '#74b9ff', '#a29bfe', '#ffeaa7',
  '#fab1a0', '#e17055', '#636e72', '#ddd', '#b2bec3',
  '#00b894', '#00cec9', '#0984e3', '#6c5ce7', '#e84393',
  '#fd79a8', '#fdcb6e', '#e17055', '#74b9ff', '#a29bfe'
];

const getFixedColor = (index) => {
  return PREDEFINED_COLORS[index % PREDEFINED_COLORS.length];
};

// 优化的tooltip格式化函数，使用缓存
let tooltipCache = new Map();
const optimizedTooltipFormatter = (params) => {
  if (!params || params.length === 0) return '';
  const time = params[0].axisValue;
  const cacheKey = `${time}_${params.length}`;
  // 检查缓存
  if (tooltipCache.has(cacheKey)) {
    return tooltipCache.get(cacheKey);
  }
  const validData = params.filter(p => p.value !== null && p.value !== undefined && p.value !== '');
  if (validData.length === 0) {
    const result = `${time}<br/>暂无数据`;
    tooltipCache.set(cacheKey, result);
    return result;
  }
  let maxVoltage = -Infinity;
  let minVoltage = Infinity;
  let maxVoltageSeries = '';
  let minVoltageSeries = '';
  validData.forEach(item => {
    const voltage = parseFloat(item.value);
    if (!isNaN(voltage)) {
      if (voltage > maxVoltage) {
        maxVoltage = voltage;
        maxVoltageSeries = item.seriesName;
      }
      if (voltage < minVoltage) {
        minVoltage = voltage;
        minVoltageSeries = item.seriesName;
      }
    }
  });
  if (maxVoltage === -Infinity || minVoltage === Infinity) {
    const result = `${time}<br/>暂无有效数据`;
    tooltipCache.set(cacheKey, result);
    return result;
  }
  const result = `
    ${time}<br/>
    <span style="color: #ff6b6b;">●</span> 最高电压：${maxVoltage.toFixed(2)}mV<br/>
    <span style="color: #ff6b6b;">●</span> 最高电压位置：${maxVoltageSeries}<br/>
    <span style="color: #4ecdc4;">●</span> 最低电压：${minVoltage.toFixed(2)}mV<br/>
    <span style="color: #4ecdc4;">●</span> 最低电压位置：${minVoltageSeries}
  `;
  // 限制缓存大小
  if (tooltipCache.size > 100) {
    tooltipCache.clear();
  }
  tooltipCache.set(cacheKey, result);
  return result;
};

// 生成240个系列的配置，使用固定颜色
const generate240Series = () => {
  const series = [];
  for (let i = 0; i < 240; i++) {
    const color = getFixedColor(i);
    series.push({
      name: `电芯${i + 1}`,
      type: 'line',
      data: [],
      itemStyle: {
        color: color
      },
      lineStyle: {
        color: color,
        width: 1
      },
      symbol: 'none',
      smooth: false,
      showSymbol: false,
      // 只在第一个系列显示标记区域
      // ...(i === 0 ? {
      //   markArea: {
      //     silent: true,
      //     label: {
      //       show: true,
      //       color: '#ffffff',
      //       fontSize: 12,
      //       fontWeight: 'bold',
      //       textShadowColor: 'rgba(0,0,0,0.8)',
      //       textShadowBlur: 2,
      //       textShadowOffsetX: 1,
      //       textShadowOffsetY: 1
      //     },
      //     itemStyle: {
      //       color: 'rgba(139, 69, 19, 0.2)',
      //       borderColor: 'rgba(139, 69, 19, 0.6)',
      //       borderWidth: 1
      //     },
      //     data: [
      //       [
      //         {
      //           name: '充电',
      //           xAxis: '08:00',
      //           itemStyle: {
      //             color: 'rgba(217, 0, 27, 0.09)',
      //             borderColor: 'rgba(139, 69, 19, 0.6)',
      //             borderWidth: 1
      //           }
      //         },
      //         {
      //           xAxis: '12:00'
      //         }
      //       ],
      //       [
      //         {
      //           name: '放电',
      //           xAxis: '16:00',
      //           itemStyle: {
      //             color: 'rgba(91, 143, 249, 0.09)',
      //             borderColor: 'rgba(25, 25, 112, 0.6)',
      //             borderWidth: 1
      //           }
      //         },
      //         {
      //           xAxis: '20:00'
      //         }
      //       ]
      //     ]
      //   }
      // } : {})
    });
  }
  return series;
};

// 双图表配置 - 电压分布统计
export const getVoltageDistributionOption = (timeAxisData = []) => {
  // 如果没有传入时间轴数据，使用空数组
  if (!timeAxisData || timeAxisData.length === 0) {
    timeAxisData = [];
  }

  return {
    title: {
      text: '单体电压趋势',
      textStyle: {
        fontSize: 16,
        color: '#fff'
      },
      left: 'center',
      top: 10,
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          show: false
        }
      },
      formatter: optimizedTooltipFormatter,
    },
    legend: {
      show: false
    },
    axisPointer: {
      link: [{ xAxisIndex: "all" }],
      label: {
        show: false
      }
    },
    grid: [
      {
        left: 60,
        right: '3%',
        top: 80,
        bottom: 60,
      }
    ],
    xAxis: [{
      type: 'category',
      data: timeAxisData,
      boundaryGap: false,
      axisLine: { onZero: true },
      axisLine: {
        lineStyle: {
          color: '#fff'
        }
      }
    }],
    yAxis: [
      {
        type: 'value',
        name: '电压(mV)',
        splitNumber: 5,
        min: 3.0,
        max: 3.6,
        nameTextStyle: {
          color: '#fff'
        },
        axisLabel: {
          color: '#fff'
        },
        axisLine: {
          lineStyle: {
            color: '#fff'
          }
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255,255,255,0.1)'
          }
        }
      }
    ],
    dataZoom: [
      {
        type: 'slider',
        show: true,
        xAxisIndex: [0],
        start: 0,
        end: 100,
        height: 20,
        bottom: 10,
        borderColor: '#ccc',
        fillerColor: 'rgba(167,183,204,0.4)',
        handleColor: '#fff',
        handleSize: '100%',
        textStyle: {
          color: '#fff'
        }
      },
      {
        type: 'inside',
        xAxisIndex: [0],
        start: 0,
        end: 20
      }
    ],
    series: generate240Series()
  };
};